import QtQuick 2.0
import QtQuick.Controls 2.15

Item {
    signal dependenciesInstalled()
    signal dependenciesInstallCanceled()
    signal dependenciesInstallError()

    Script {
        id: script

        readonly property int modeCheck: 0
        readonly property int modeInstall: 1
        property int mode: modeCheck

        onFinished: {
            console.log(`DEP Script finished with code: ${code}`)

            switch (mode) {
                case modeCheck:
                    onCheckFinished(code, output)
                    break

                case modeInstall:
                    ui.log(output)
                    onInstallFinished(code)
                    break
            }
        }


        function onCheckFinished(code, output) {
            if (code === 127) {
                // script not found
                ui.log(qsTr("Failed to execute dependencies script"))
                dependenciesInstallError()
            } else if (code !== 0) {
                ui.log(qsTr("Dependencies missing:") + " " + output)
                textDialog.text = qsTr("Some required dependencies are missing:") + " <b>"
                        + output + "</b> .<br/>"
                        + qsTr("Click OK to try installing them automatically, or Cancel to install them manually")
                dialog.open()
            } else {
                dependenciesInstalled()
            }
        }

        function onInstallFinished(code) {
            if (code !== 0) {
                dependenciesInstallError()
            } else {
                dependenciesInstalled()
            }
        }

        function install() {
            ui.log(qsTr("Installing dependencies..."))
            mode = modeInstall
            script.execScript("deps", "install")
        }
    }

    Dialog {
        id: dialog
        anchors.centerIn: parent
        title: window.title
        modal: true
        focus: true
        standardButtons: Dialog.Ok | Dialog.Cancel

        TextArea {
            id: textDialog
            readOnly: true
            selectByMouse: true
            wrapMode: Text.WordWrap
            anchors.fill: parent
            implicitWidth: block * 8
            textFormat: "RichText"
        }

        onAccepted: script.install()
        onRejected: dependenciesInstallCanceled()
    }

    function check() {
        script.mode = script.modeCheck
        script.execScript("deps", "check")
    }
}
